package com.peaksport.framework.extend.spring;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.peaksport.framework.exception.PKDevException;

/**
 * 
 * @author jinbin_guo  2019年5月28日 下午12:26:39
 *
 */
@Component
public class PKApplicationContext implements ApplicationContextAware {
	
	
	private static ApplicationContext applicationContext;
	private static String microService;
	private static String port;
	private static String hostAddr;
	private static String hostName;
	
	@Autowired
	private Environment environment;  
	
	public void setApplicationContext(ApplicationContext appCtx) {
		applicationContext = appCtx;
		//获取微服务名&端口
		microService = environment.getProperty("spring.application.name");
		port = environment.getProperty("server.port");
	}
	public static ApplicationContext getApplicationContext(){
		return applicationContext;
	}
	
	/**
	 * 获取上下文实例化的bean
	 * @param clazz
	 * @return
	 */
	public static Object getBean(Class<?> clazz) {
		return applicationContext.getBean(clazz);
	}
	
	/**
	 * 获取主机IP
	 * @return
	 */
	public static String getHostIP() {
		if (hostAddr != null) return hostAddr;
		InetAddress localHost = null;
		try {
		  localHost = Inet4Address.getLocalHost();
		} catch (UnknownHostException e) {
		  throw PKDevException.throwException("获取主机信息异常:%s", e.getMessage());
		}
		hostAddr = localHost.getHostAddress();  // 返回格式为：xxx.xxx.xxx
		return hostAddr;
	}
	/**
	 * 获取主机名
	 * @return
	 */
	public static String getHostName() {
		if (hostName != null) return hostName;
		InetAddress localHost = null;
		try {
		  localHost = Inet4Address.getLocalHost();
		} catch (UnknownHostException e) {
		  throw PKDevException.throwException("获取主机信息异常:%s", e.getMessage());
		}
		hostName = localHost.getHostName();
		return hostName;
	}
	/**
	 * 获取微服务名
	 * @return
	 */
	public static String getMicroService() {
		return microService;
	}
	
	/**
	 * 获取服务端口
	 * @return
	 */
	public static String getPort() {
		return port;
	}
}